<script setup>
import { ref } from 'vue'
import { CateAddService, CatePutService } from '@/api/user.js'

const dialogFormVisible = ref(false)

const cateForm = ref({
  id: '',
  cate_name: '',
  cate_alias: '',
})

const refForm = ref()

const emit = defineEmits(['success'])
const submitCate = async () => {
  await refForm.value.validate()
  console.log(cateForm.value)

  if (cateForm.value.id) {
    await CatePutService(cateForm.value)
    ElMessage.success("更新文章分类成功")
  } else {
    await CateAddService(cateForm.value)
    ElMessage.success("添加文章分类成功")
  }
  dialogFormVisible.value = false
  emit('success')
}

const cateRule = {
  cate_name: [
    { required: true, message: '分类名称不能为空', trigger: 'blur' },
    {
      pattern: /^\S{1,10}$/,
      message: "分类名称必须是1-10位的非空字符",
      trigger: "blur",
    }
  ],
  cate_alias: [
    { required: true, message: '分类别名不能为空', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]{1,15}$/,
      message: "分类别名必须是1-15位的字母或数字",
      trigger: "blur",
    }
  ],
}

const open = (row) => {
  if (row.id) {
    cateForm.value = { ...row }
  }
  else {
    cateForm.value = {}
  }
  dialogFormVisible.value = true
  console.log(cateForm.value)
}

defineExpose({
  open,
})


</script>

<template>
  <el-dialog v-model="dialogFormVisible" title="分类" width="500">
    <el-form
      :model="cateForm"
      label-width="auto"
      :rules="cateRule"
      ref="refForm">
      <el-form-item label="分类名称" prop="cate_name" >
        <el-input placeholder="请输入分类名称" v-model="cateForm.cate_name" name="cate_name" />
      </el-form-item>
      <el-form-item label="分类别名" prop="cate_alias">
        <el-input placeholder="请输入分类别名" v-model="cateForm.cate_alias" name="cate_alias" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCate"> 提交 </el-button>
      </div>
    </template>
  </el-dialog>
</template>
